package com.mapbased.wfw.components;

import java.io.*;
import java.util.*;

import com.mapbased.wfw.*;
import com.mapbased.wfw.PageLoader.*;
import org.dom4j.*;

/**
 * <p>Title: </p>
 *
 * <p>Description:根据目录结构自动生成导航菜单 </p>
 *
 * <p>Copyright: Copyright (c) 2008</p>
 *
 * <p>Company: mapbased.com</p>
 *
 * @author chy_hs(Baily)
 * @version 1.0
 */
public class FSMenu
      extends Component
{
    static class ListItem implements Comparable {
        public ListItem(String showName,String path)
        {
            this.showName=showName;
            this.path=path;
        }

        String showName;
        String path;
        int index=0;
        /**
         * Compares this object with the specified object for order.
         *
         * @param o the object to be compared.
         * @return a negative integer, zero, or a positive integer as this
         *   object is less than, equal to, or greater than the specified
         *   object.
         * @todo Implement this java.lang.Comparable method
         */
        public int compareTo(Object o) {
            return -((ListItem)o).index+this.index;
        }

    }

    private ListItem[] listItems;

    /**
     * a component can choose to parse an element or not.
     *
     * @param ele Element
     * @param lc PageLoader
     * @return Element or null:if wanna page loader parse the
     *   component,return the ele, else return null
     * @todo Implement this com.mapbased.wfw.Component method
     */
    public Element parseXml(Element ele,LoadContext lc)
    {
     String pageExtName=  this.fetchAttribute(ele,"extname",".html");
        String path=ele.attributeValue("path");
        if(path==null)
        {

            path=lc.pagepath;
        }
        else
        {
            ele.remove(ele.attribute("path"));

        }

        String DPP=lc.loader.getDefaulPagePath();
        File f=new File(DPP+path+".xml");

        java.util.Properties p=new Properties();
        FileInputStream bis=null;
        try
        { //small file,no cache is needed
            bis= new java.io.FileInputStream(f);
            p.loadFromXML(bis);
        }
        catch(FileNotFoundException ex)
        {
            try
            {
                f.createNewFile();
            }
            catch(IOException ex1)
            {

            }

        }
        catch(IOException e)
        {
            lc.loader.getGlobal().getServletContext().log("IOEX while loading :"
                  +f.getAbsolutePath());
        }
        finally
        {
            try
            {
                if(bis!=null)
                bis.close();
            }
            catch(IOException ex4)
            {
            }
        }
        File[] fs=f.getParentFile().listFiles(new FileFilter()
        {
            public boolean accept(File p)
            {
               // p.listFiles(new FilenameFilter(){});
                return p.isDirectory();
            }
        });
        if (fs==null)
        {
            fs=new File[]{};
        }
        this.listItems=new ListItem[fs.length];
        boolean write=false;
        for(int i=0;i<fs.length;i++)
        {
            String s=fs[i].getName();
            if(p.getProperty(s)==null)
            {
                p.setProperty(s,s);
                p.setProperty(s+"_index","0");
                write=true;
            }



        }

        if(f.length()<2||write)
        {
            FileOutputStream fos=null;
            try
            {
                fos=new java.io.FileOutputStream(f);
                p.storeToXML(fos,
                             "Translate value to label to display");
            }
            catch(IOException ex2)
            {
                ex2.printStackTrace();
            }
            finally
            {
                if(fos!=null)
                {
                    try
                    {
                        fos.close();
                    }
                    catch(IOException ex3)
                    {
                    }
                }
            }
        }
        java.util.ArrayList list=new ArrayList();

        for (Object elem : p.entrySet())
        {
            java.util.Map.Entry e = (java.util.Map.Entry) elem;
            String k = e.getKey().toString();
            if (k.endsWith("_index"))
            {
                continue;
            }
            int index=Integer.parseInt( p.getProperty(k+"_index","0"));
            if(index>=0)
            {
                try {
                    ListItem l = new ListItem(p.getProperty(k, k)
                                              ,
                                              new StringBuilder(f.getParent().
                            substring(DPP.length()))
                                              .append("/")
                                              .append(com.mapbased.wfw.Util.
                            urlEncodeExcludeDelimiter(k, "UTF-8")).append(p.
                            getProperty(k + "_page", "/index" +pageExtName ))
                                              .toString());
                    l.index = index;
                    list.add(l);
                } catch (UnsupportedEncodingException ex5) {
                    ex5.printStackTrace();
                }

            }



        }
        java.util.Collections.sort(list);
        this.listItems=(ListItem[])list.toArray( new ListItem[list.size()]);


        List cl=ele.elements();
        if(cl.size()!=2)
        {
            throw new RuntimeException(
                  "Must have two children,one for general,one for selected!");
        }
        LoadContext nlc=new LoadContext(lc);
        lc.loader.parseElement((Element) cl.get(0),nlc);

        this.general=nlc.getSegments();
        nlc=new LoadContext(lc);
        lc.loader.parseElement((Element) cl.get(1),nlc);
        this.selected=nlc.getSegments();

        return null;
    }

    Object[] general;
    Object[] selected;

    /**
     * render
     *
     * @param rc RenderContext
     * @throws IOException
     * @todo Implement this com.mapbased.wfw.Component method
     */
    public void render(RenderContext rc)
          throws IOException
    {
        for(int i=0;i<this.listItems.length;i++)
        {
            ListItem li=this.listItems[i];
            rc.putParam("_path",rc.getRequest().getContextPath()+  li.path);
            rc.putParam("_showName",li.showName);

            if(rc.getRequest().getServletPath().indexOf(li.path)>=0)
            {
                defalutRenderBehavior(rc,this.selected);
            }
            else
            {
                defalutRenderBehavior(rc,this.general);
            }

        }

    }

    /**
     * renderHeader
     *
     * @param context RenderContext
     * @param sb StringBuffer
     * @param m Map
     * @todo Implement this com.mapbased.wfw.Component method
     */
    public void renderHeader(RenderContext context,StringBuffer sb,Map m)
    {
    }

    public static void main(String[] args)
    {
        FSMenu fsmenu=new FSMenu();
    }
}
